package com.bawei.module_live.version2

import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.mvi.base.BaseActivity
import com.bawei.lib_common.websocket.LiveWebSocketManager
import com.bawei.lib_net.RetrofitFactory
import com.bawei.module_live.R
import com.bawei.module_live.databinding.ActivityLiveingBinding
import com.bawei.module_live.ui.dialog.RedPacketGrabDialog
import com.bawei.module_live.version2.adapter.LiveRoomAdapter
import com.bawei.module_live.version2.mvi.intent.LiveIntent
import com.bawei.module_live.version2.mvi.model.api.LiveApi
import com.bawei.module_live.version2.mvi.model.entity.LiveEntity2
import com.bawei.module_live.version2.mvi.state.LiveState
import com.bawei.module_live.version2.mvi.viewmodel.LiveViewModel
import com.blankj.utilcode.util.ToastUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import kotlin.math.roundToInt
import kotlin.properties.Delegates
import com.opensource.svgaplayer.SVGAImageView
import android.os.Handler
import android.os.Looper

@Route(path = "/module_live/LiveingActivity")
class LiveingActivity : BaseActivity() {
    private lateinit var liveViewModel: LiveViewModel
    private val binding: ActivityLiveingBinding by lazy {
        ActivityLiveingBinding.inflate(layoutInflater)
    }
    private var liveRooms: ArrayList<LiveEntity2> = arrayListOf()
    private lateinit var adapter: LiveRoomAdapter
    private var roomId: String? = null
    private var username="用户名"
    private var userId=5
    private var webSocket: WebSocket? = null
    private var position:Int=0
    private lateinit var svgaImageView: SVGAImageView
    private var num=0


    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()


        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
        // 数据加载前，显示占位符，隐藏列表
        binding.tvNoData.visibility = View.VISIBLE
        binding.rv.visibility = View.GONE
        svgaImageView = binding.root.findViewById(R.id.svgaImageView)
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.liveFlow_.collect {
                    when (it) {
                        is LiveState.Init -> {
                            binding.tvNoData.visibility = View.VISIBLE
                            binding.rv.visibility = View.GONE
                        }
                        is LiveState.Empty -> {
                            binding.tvNoData.visibility = View.VISIBLE
                            binding.rv.visibility = View.GONE
                        }
                        is LiveState.Failed -> {
//                            binding.tvNoData.text = "加载失败，请重试"
                            binding.tvNoData.setImageResource(R.drawable.load_failed) // 换成失败图片
                            binding.tvNoData.visibility = View.VISIBLE
                            binding.rv.visibility = View.GONE
                        }
                        is LiveState.VideoSuccess -> {
                            it.list?.let { list ->
                                if (list.isNotEmpty()) {
                                    liveRooms.clear()
                                    liveRooms.addAll(list)
                                    adapter.updateData(list)
                                    binding.tvNoData.visibility = View.GONE
                                    binding.rv.visibility = View.VISIBLE
                                } else {
//                                    binding.tvNoData.text = "暂无直播间"
                                    binding.tvNoData.setImageResource(R.drawable.load_failed) // 换成失败图片
                                    binding.tvNoData.visibility = View.VISIBLE
                                    binding.rv.visibility = View.GONE
                                }
                            } ?: run {
//                                binding.tvNoData.text = "暂无直播间"
                                binding.tvNoData.setImageResource(R.drawable.load_failed) // 换成失败图片
                                binding.tvNoData.visibility = View.VISIBLE
                                binding.rv.visibility = View.GONE
                            }
                        }
                        is LiveState.GetRedPacketSuccess->{
                            if (it.bl){
                                ToastUtils.showShort("参与抽奖成功")
                            }
                        }
                    }
                }
            }
        }
        // 初始化 RecyclerView
        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rv.layoutManager = layoutManager
        adapter = LiveRoomAdapter(liveRooms, svgaImageView)
        binding.rv.adapter = adapter

        // 关键：添加整页吸附
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(binding.rv)

        // 修改1：优化后的滚动监听
        binding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                     position = (recyclerView.layoutManager as LinearLayoutManager)
                        .findFirstCompletelyVisibleItemPosition()
                    if (position != RecyclerView.NO_POSITION && position < liveRooms.size) {
                        val newRoomId = liveRooms[position].room_id


                            val holder = binding.rv.findViewHolderForAdapterPosition(position)
                            if (holder is LiveRoomAdapter.LiveRoomViewHolder) {
                                Log.d("ItemOnlinePolling", "切换到新item，开始轮询 roomId=$newRoomId")
                                adapter.onCurrentItemChanged(holder)

                            }


                    }
                }
            }
        })

        // 修改2：优化初始化逻辑
        binding.rv.post {
            val position = (binding.rv.layoutManager as LinearLayoutManager)
                .findFirstCompletelyVisibleItemPosition()
            if (position != RecyclerView.NO_POSITION && position < liveRooms.size) {
                val newRoomId = liveRooms[position].room_id


                val holder = binding.rv.findViewHolderForAdapterPosition(position)
                if (holder is LiveRoomAdapter.LiveRoomViewHolder) {
                    Log.d("ItemOnlinePolling", "首次加载，开始轮询 roomId=$newRoomId")
                    adapter.onCurrentItemChanged(holder)
                }
            }
        }
    }


    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                liveViewModel.intents.send(LiveIntent.getSimpleType)
                liveViewModel.handleIntent()
            }
        }
        initWebSocket()

        adapter.onItemClickListener = { viewId, position, item ->
            when (viewId) {
                R.id.red_envelope -> {
                    // 处理红包点击
                    handleRedEnvelopeClick(position, item)
                }
                R.id.player_view -> {
                    // 处理播放器点击
                    Toast.makeText(this, "点击了位置$position 的播放器", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    // 新增：处理红包点击事件
    private fun handleRedEnvelopeClick(position: Int, item: LiveEntity2) {
        // 显示抢红包弹窗
        showGrabRedPacketDialog(position, item)


    }

    // 新增：显示抢红包弹窗
    private fun showGrabRedPacketDialog(position: Int, item: LiveEntity2) {
        val dialog = RedPacketGrabDialog(
            context = this,
            onGrabClick = {
                // 抢红包逻辑
                grabRedPacket(position, item)
            },
            onCloseClick = {
                // 关闭弹窗
                Toast.makeText(this, "错过了红包", Toast.LENGTH_SHORT).show()
            }
        )
        dialog.show()
        // 设置弹窗内容
        dialog.setTitle("主播发红包啦！")
        dialog.setDescription("点击抢红包，手快有手慢无！")

    }

    // 新增：抢红包逻辑
    private fun grabRedPacket(position: Int, item: LiveEntity2) {
        // 这里可以调用API抢红包
        Toast.makeText(this, "正在抢红包...", Toast.LENGTH_SHORT).show()
        
        // 模拟抢红包成功
        lifecycleScope.launch {
            // 延迟1秒模拟网络请求
            kotlinx.coroutines.delay(1000)
            
            runOnUiThread {
                // 抢红包成功，隐藏红包图标
                val holder = binding.rv.findViewHolderForAdapterPosition(position)
                if (holder is LiveRoomAdapter.LiveRoomViewHolder) {
                    adapter.hideRedEnvelopeForHolder(holder)
                }
                
                // 显示抢红包结果
                showGrabResult()
            }
        }
    }

    // 新增：显示抢红包结果
    private fun showGrabResult() {
        val randomAmount = (1..num).random() // 随机金额1-100
        val dialog = AlertDialog.Builder(this)
            .setTitle("抢红包成功！")
            .setMessage("恭喜你抢到了 ${randomAmount} 钻石！")
            .setPositiveButton("确定") { dialog, which ->
                dialog.dismiss()
            }
            .create()
        
        dialog.show()
    }

    private fun showRedPacketDialog(count: Int, diamond: Int) {
        // 显示红包弹窗
        showRedPacketPopup(count, diamond)
        
        // 显示当前可见item的红包图标
        showRedEnvelopeForCurrentItem()
    }

    // 新增：显示红包弹窗的方法
    private fun showRedPacketPopup(count: Int, diamond: Int) {
        // 这里可以显示你的红包弹窗
        Toast.makeText(this, "收到红包！主播发了${count}个红包，每个${diamond} 钻石", Toast.LENGTH_LONG).show()
    }

    // 新增：显示当前可见item的红包图标
    private fun showRedEnvelopeForCurrentItem() {
        val layoutManager = binding.rv.layoutManager as? LinearLayoutManager
        val position = layoutManager?.findFirstCompletelyVisibleItemPosition() ?: -1
        
        if (position != RecyclerView.NO_POSITION && position < liveRooms.size) {
            val holder = binding.rv.findViewHolderForAdapterPosition(position)
            if (holder is LiveRoomAdapter.LiveRoomViewHolder) {
                // 显示红包图标
                adapter.showRedEnvelopeForHolder(holder)
                
                // 可选：设置倒计时
                startRedEnvelopeCountdown(holder)
                
                Log.d("RedEnvelope", "显示红包在位置: $position")
            }
        }
    }

    // 新增：红包倒计时
    private fun startRedEnvelopeCountdown(holder: LiveRoomAdapter.LiveRoomViewHolder) {
        var countdown = 10 // 10秒倒计时
        
        val timer = java.util.Timer()
        val timerTask = object : java.util.TimerTask() {
            override fun run() {
                runOnUiThread {
                    if (countdown > 0) {
                        val minutes = countdown / 60
                        val seconds = countdown % 60
                        holder.redEnvelopeTime.text = String.format("%02d:%02d", minutes, seconds)
                        countdown--
                    } else {
                        // 倒计时结束，隐藏红包
                        adapter.hideRedEnvelopeForHolder(holder)
                        timer.cancel()
                    }
                }
            }
        }
        
        timer.schedule(timerTask, 0, 1000)
    }


    override fun onDestroy() {


        // 释放播放器资源
        adapter.releaseAllPlayers()
        webSocket?.close(1000, "bye")
        webSocket?.cancel()  // 比close()更强制性地中断连接
        webSocket = null

        // 原有销毁逻辑
        adapter.releaseAllPlayers()
        super.onDestroy()
    }
    private fun initWebSocket() {
        val client = OkHttpClient()
        val request: Request = Request.Builder()
            .url("ws://10.161.9.80:7015/liveRoom/websocket/${111}/${5}")
            .build()
        webSocket = client.newWebSocket(request, object : WebSocketListener() {
            override fun onMessage(webSocket: WebSocket, text: String) {
                //收到文本消息
                Log.d("Websocket", "onMessage: "+text)
                val json= JSONObject(text)
                val type=json.optInt("type")
                if (type==5){
                    val data=json.optJSONObject("data")
                    val username=data?.optString("username")
                    if (!username.isNullOrEmpty()){
                        runOnUiThread {
                            ToastUtils.showShort("$username 加入直播间")
                        }
                    }

                }
                if (type==1){
                    val data=json.optJSONObject("data")
                    val roomId=data?.optString("room_id")
                    val count=data?.optInt("count")
                    val money=data?.optDouble("money")
                    val time=data?.optInt("time")
                    val createTime=data?.optString("createTime")

                    num= (money!!*count!!).toInt()
                    runOnUiThread {
                        showRedPacketDialog(count!!,  money!!.roundToInt())
                    }
                }

            }

            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {

            }

            override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
                // 处理断线重连等
                //Log.e("WebSocket", "连接失败: ${t.message}")
            }

            override fun onOpen(webSocket: WebSocket, response: Response) {
                Log.d("WebSocket","redPacket---open")
                Log.d("WebSocket", "连接已建立，房间号:$roomId")
                Log.d("WebSocket", webSocket.request().url.toString())

                val joinMsg=JSONObject().apply {
                    put("type","join")
                    put("userId",userId)
                    put("username",username)
                }
                webSocket.send(joinMsg.toString())
            }

            override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
                Log.d("WebSocket","redPacket---close")
            }

        })
    }



}